package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.common.SMSSendCode;
import com.itheima.entity.Orders;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        //1.接收数据
        log.info("接收到的手机号为:{}",phone);
        if (phone != null && phone.length() != 0){
            //2.生成一个验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();

            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

            log.info("phone:{},code:{}",phone,code);
            //2.1 服务器要存储
//            session.setAttribute(phone,code);//这个手机号对应的验证码
            //2.2 客户要收到-发送短信验证码
            try {
//                SMSSendCode.sendCode(phone,code);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return R.success(code);
        }
        return R.error("该手机号不存在，请重试");
    }

    /**
     * 前台登录
     * 判断 验证码
     * 查询手机号判断是否有数据
     *      如果没有值---注册---登录
     *      有值 -------登录
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody User user,HttpSession session){
        //1.接收信息
        log.info("登录的信息为:{}",user);
        //2.手机号、验证码
        String phone = user.getPhone();
        String code = user.getCode();
        //3.如何判断登录成功
        //判断这个验证码是否正常（输入了，你输入的和session中必须一致）
//        String sessioncode = (String) session.getAttribute(phone);
        Object sessioncode = redisTemplate.opsForValue().get(phone);
        if (!sessioncode.equals(code)){
            log.info("您输入的手机验证码不正确");
            return R.error("您输入的手机验证码不正确");
        }
        //判断一下这个手机号是否存在，不存在，我就给你注册
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        User one = userService.getOne(wrapper);

        if (one==null){
            log.info("您输入的手机未注册，我帮你注册");
            user.setStatus(1);
            user.setName("用户_"+phone);
            userService.save(user);
            one=user;
        }
        //登录-往session中存入数据
        session.setAttribute("empId",one.getId());
        //清理redis code缓存
        redisTemplate.delete(phone);

        return R.success(one);
    }
}
